package com.situ.web.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.situ.web.common.ServerResponse;
import com.situ.web.entity.Department;
import com.situ.web.entity.PageBean;
import com.situ.web.entity.Role;
import com.situ.web.entity.User;
import com.situ.web.service.IUserService;
import com.situ.web.service.impl.UserServiceImpl;
import com.situ.web.util.JSONUtil;

@Controller
@RequestMapping(value = "/user")
public class UserController {
	private IUserService userService = new UserServiceImpl();
	
	@RequestMapping(value = "/pageList")
	private String pageList(String pageNo,String pageSize,Model model) {
		model.addAttribute("pageNo", pageNo);
		model.addAttribute("pageSize", pageSize);
		if (null == pageNo || "".equals(pageNo)) {
			pageNo = "1";
		}
		if (null == pageSize || "".equals(pageSize)) {
			pageSize = "3";
		}
		
		PageBean pageBean = userService.pageList(Integer.parseInt(pageNo),Integer.parseInt(pageSize));
		
		model.addAttribute("pageBean", pageBean);
		
		return "forward: user_page_list";
		
	}
	
	private void search(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String searchName = req.getParameter("searchName");
		List<Map<String, Object>> list = userService.search(searchName);
		
		req.setAttribute("list", list);
		req.getRequestDispatcher("user_search.jsp").forward(req, resp);
	}
	
	private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String id = req.getParameter("id");

		boolean isSuccess = userService.deleteById(Integer.parseInt(id));
		
		ServerResponse serverResponse = null;
		if (isSuccess) {
			serverResponse = ServerResponse.createSuccess("删除成功");
		} else {
			serverResponse = ServerResponse.createError("删除失败");
		}
		JSONUtil.obj2Json(resp, serverResponse);
	}
	
	private void toUpdate(String updateId,Model model) {
			model.addAttribute("updateId",updateId);
			
			User user = userService.selectById(Integer.parseInt(updateId));
			System.out.println(user);
			
			model.addAttribute("user", user);
	}
	


}
